
import {Config} from 'config.js';

class Token{

  constructor() {
    this.tokenUrl = Config.requestUrl+'token/user';
    this.verifyUrl = Config.requestUrl+'token/verify';
  }

  verify(){
    var token = wx.getStorageSync('token');
    if(!token){
      this._getTokenFormServer();
    }else{
      this._verifyFormServer(token);
    }
  }

  // 获取令牌
  _getTokenFormServer(callBack){
    var that = this;
    wx.login({
      success: function (res) {
        wx.request({
          url: that.tokenUrl,
          data: {
            'code': res.code
          },
          method: 'POST',
          success: function (res) {
            wx.setStorageSync('token', res.data.token);
            callBack && callBack(res.data.token);
          }
        })
      },
    })
  }

  // 校验服务器token是否正确
  _verifyFormServer(token){
    var that = this;
    wx.request({
      url: that.verifyUrl,
      method:'POST',
      data:{
        token:token,
      },
      success:function(res){
        var valid = res.data.isValid;
        if (!valid){
          that._getTokenFormServer();
        }
      }
    })
  }

}

export { Token }